<!DOCTYPE html>
<html>

<head>
 <meta charset="utf-8">
 <title>首页</title>
 <link rel="stylesheet" href="/public/layui/css/layui.css">
 <link rel="stylesheet" href="/public/css/style.css">
</head>

<body>
 <div class="content">
  <div class="flyer" id="flyer">

  </div>

  <div class="top">
   <div class="logo cp">
    SHOPPING
   </div>
   <div>
    <input type="text" name="title" required lay-verify="required" placeholder="请输入商品名称" autocomplete="off"
     class="layui-input txt_title">
   </div>
   <div class="topRight">
    <div class="ml cart hov cp" id="cart">
     <i class="layui-icon">&#xe657;</i>
    </div>

    <div class="l">
     <div class="ml order hov cp">我的订单</div>
     <div class="user dfcn cp ">
      <img src="../public/img/1722761748697.jpg" class="layui-nav-img ml">
      <span class="hov admin">-</span>
      <div class="ml logout cp hov">退出</div>
     </div>
    </div>
    <div class="nl">
     <a class="ml" href="./login.html">欢迎登录</a>
     <a class="ml" href="./register.html">立即注册</a>
    </div>
   </div>
  </div>
  <div class="layui-row layui-col-space10 box" id="box">
  </div>
 </div>
 </div>
 <div id="cardList">
  <h2>购物车</h2>
  <div class="close cp">
   <i class="layui-icon" style="font-size: 24px; ">&#x1006;</i>
  </div>
  <div class="cardBox">

  </div>
  <div class="foot">
   <h3>总价</h3>
   <h1>0￥</h1>
  </div>
  <button class="submit">提交订单</button>
 </div>

 <div class="bg"></div>
 <script src="/public/layui/layui.js"></script>
 <script>
  layui.config({
   base: '/public/js/'
  }).use(['layer', 'form', 'jquery', 'flow', 'commonLayer', 'element'], function () {
   var layer = layui.layer, form = layui.form, $ = layui.jquery;
   var element = layui.element;
   var commonLayer = layui.commonLayer();
   let isCart = false
   var flow = layui.flow;
   let user = {}
   let queryParams = {
    page: 1,
    limit: 10000
   }, dataList = [];
   const flyerTime = 500
   let flyerFlag = false
   let cardList = JSON.parse(window.localStorage.getItem('cardList')) || [];

   $('.logo').click(function () {
    window.location.href = '/'
   })
   const flyer = (_this) => {
    const _card = $('#cart')
    console.log(_this.offset(), _card.offset(), $('#flyer'), $('#flyer')[0].clientWidth);
    $('#flyer').css({
     left: _this.offset().left - $('#flyer')[0].clientWidth / 2 + 'px',
     top: _this.offset().top - $('#flyer')[0].clientHeight / 2 + 'px',
     display: 'block'
    })
    setTimeout(() => {
     $('#flyer').css({
      transition: 'all .5s',
      left: 'calc(100vw - 240px)',
      top: '0px',
     })
    }, 0);
    setTimeout(() => {
     $('#flyer').css({
      transition: 'none',
      display: 'none'
     })
    }, flyerTime);
   }
   const getList = () => {
    if (isCart) {
     $.ajax({
      method: 'get',
      url: `/api/auth/order`,
      data: {
       ...queryParams,
       userId: user._id
      },
      headers: {
       Authorization: 'Bearer ' + sessionStorage.getItem('token')
      },
      success: (ret) => {
       if (ret.data) {
        dataList = ret.data
       }
       dataRender()
      }
     })
    } else {
     $.ajax({
      method: 'get',
      url: `/api/auth/good`,
      data: queryParams,
      headers: {
       Authorization: 'Bearer ' + sessionStorage.getItem('token')
      },
      success: (ret) => {
       if (ret.data) {
        dataList = ret.data
       }
       dataRender()
      }
     })
    }

   }

   $('.order').click(function () {
    if (!user._id) {
     commonLayer.errorMsg('请先登录，登录后即可提交订单')
     return
    }
    isCart = !isCart;
    if (isCart) {
     $('.order').text('商城')
    } else {
     $('.order').text('我的订单')
    }
    getList()
   })
   $('.cart').click(function () {
    $('.bg').css({ 'display': 'block' })
    $('#cardList').css({ 'display': 'flex' })
    setTimeout(() => {
     $('#cardList').css({ 'width': '40%' })
    }, 0);
   })
   $('.close').click(function () {
    $('.bg').css({ 'display': 'none' })
    $('#cardList').css({ 'width': '0%' })
    setTimeout(() => {
     $('#cardList').css({ 'display': 'none' })
    }, 400);
   })
   $('.submit').click(function () {
    if (!user._id) {
     commonLayer.errorMsg('请先登录，登录后即可提交订单')
     return
    }
    const carts = cardList.map(c => {
     return {
      goodId: c._id,
      title: c.title,
      price: c.price,
      tip: c.tip,
      num: c.num,
      img: c.img
     }
    })

    $.ajax({
     method: 'post',
     url: `/api/auth/order`,
     data: {
      userId: user._id,
      price: parseFloat($('.foot h1').text()) || 0,
      carts: JSON.stringify(carts)
     },
     dataType: 'json',
     headers: {
      Authorization: 'Bearer ' + sessionStorage.getItem('token')
     },
     success: (ret) => {
      if (ret.success) {
       commonLayer.successMsg('提交成功')
       cardList = []
       viewCardBox()
      } else {
       commonLayer.errorMsg(ret.message || '网络开了会差,请稍后再试')
      }
     }
    })
   })

   const dataRender = function () {
    let str = ''
    if (isCart) {
     $('.txt_title').css({ 'display': 'none' })
     if (!dataList.length) {
      str = '暂无订单'
     }
     dataList.forEach((c, i) => {
      str += `<div class="layui-col-xs24">
				<div class="item item1 dfjc">
					<div style="width: 100px;text-align: center;">${i + 1}</div>
					<div class="layui-collapse" lay-accordion style="width: 100%;">
						<div class="layui-colla-item">
							<h2 class="layui-colla-title">商品</h2>
							<div class="layui-colla-content">
								<div class="dfjc" style="flex-direction: column;">
						`

      c.carts.forEach(v => {
       str += `<div class='dfjc layui-colla-content layui-show'
										style="width: 100%;margin-bottom:10px;display: flex !important;">
										<img src="${v.img}" alt="" style="width: 120px;height: 120px;">
										<div style="flex: 1;margin: 0 20px;">
											<div class="title">${v.title}</div>
											<div class="price" style="justify-content: flex-start;align-items: center;">
												<div><span>${v.price}</span>￥</div>
												<div style="margin: 0 10px;">*${v.num}</div>
											</div>
											<div class="tip ell" style="flex: 1;">${v.tip}</div>
										</div>
									</div>`
      })

      str += `</div>
							</div>
						</div>
					</div>
					<div style="width: 100px;text-align: center;"><span>${c.price}</span>￥</div>
				</div>
			</div>`
     })
    } else {
     $('.txt_title').css({ 'display': 'block' })

     dataList.forEach((c, i) => {
      str += `<div class="layui-col-xs6 layui-col-sm3 layui-col-md2">
						<div class="item" inx="${i}">
				<img src="${c.img}" alt="">
				<div class="title">${c.title}</div>
				<div class="price">
					<div><span>${c.price}</span>￥</div>
					<div>剩余:${c.total}</div>
				</div>
				<div class="tip ell">${c.tip}</div>
				<i class="layui-icon push" inx="${i}">&#xe654;</i>
			</div></div>`
     })
    }

    $('.box').html(str)

    element.render({
     elem: '.box'
    })
    $('.item').click(function () {
     const data = dataList[parseInt($(this).attr('inx'))]
     window.location.href = `./goodDetail.html?id=${data._id}`
    })
    $('.push').click(function (e) {
     e.stopPropagation();
     if (flyerFlag) {
      commonLayer.warnMsg('点击过快,请稍后再试')
      return
     }
     flyerFlag = true;
     setTimeout(() => {
      flyerFlag = false
     }, flyerTime);
     const data = dataList[parseInt($(this).attr('inx'))]
     $('#flyer').css({
      display: 'none'
     })
     $('#flyer').html(`<img src="${data.img}" alt="">`)

     flyer($(this))
     let flag = true;
     cardList.forEach(c => {
      if (c._id == data._id) {
       c.num += 1;
       flag = false
      }
     })
     if (flag) {
      cardList.push({
       ...data,
       num: 1
      })
     }
     viewCardBox()
    })
   }
   $('.txt_title').blur(function () {
    queryParams.title = $(this).val()
    getList()
   })
   const viewCardBox = () => {
    let str = '', total = 0
    window.localStorage.setItem('cardList', JSON.stringify(cardList))
    if (cardList.length == 0) {
     str = '<div class="empty">暂无商品，请前往添加</div>'
    }
    cardList.forEach((c, i) => {
     total += c.num * c.price
     str += `<div class="cardItem">
				<img src="${c.img}" alt="">
				<div class="cen">
					<h2>${c.title}</h2>
					<span>${c.price}￥</span>
					<p class="ell">${c.tip}</p>
				</div>
				<div class="r">
					<div class="del" inx='${i}'>-</div>
					<input type="text" value="${c.num}" readonly>
					<div class="add" inx='${i}'>+</div>
				</div>
				<div class="remove cp" inx='${i}'>
			<i class="layui-icon" style="font-size: 18px; ">&#x1006;</i>
		</div>
			</div>`
    })
    $(".cardBox").html(str)
    $('.foot h1').html(total + '￥')
    $('.del').click(function () {
     const i = parseInt($(this).attr('inx'))
     const data = cardList[i]
     data.num = --data.num || 1;
     viewCardBox()
    })
    $('.add').click(function () {
     const i = parseInt($(this).attr('inx'))
     const data = cardList[i]
     data.num = ++data.num > data.total ? data.total : data.num;
     viewCardBox()
    })
    $('.remove').click(function () {
     const i = parseInt($(this).attr('inx'))
     cardList = cardList.filter((c, j) => i != j)
     viewCardBox()
    })
   }

   const init = () => {
    user = JSON.parse(sessionStorage.getItem('user') || "{}")
    if (user._id) {
     $('.user span').text(user.username)
     $('.user img')[0].src = user.img
     $('.l').css({ display: 'flex' })
     $('.nl').css({ display: 'none' })
    } else {
     $('.nl').css({ display: 'flex' })
     $('.l').css({ display: 'none' })
    }
    getList()
    viewCardBox()
   }
   init()
   $('.logout').click(function () {
    sessionStorage.removeItem('user')
    sessionStorage.removeItem('token')
    isCart = false
    init()
   });
   $('.admin').click(c => {
    if (user.username == 'admin') {
     window.location.href = './admin.html'
    }
   })
  });


 </script>
</body>

</html>